package com.nlx.notes.support.util;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class LargeFileScanner {

    // 文件信息类
    static class FileInfo {
        String path;
        long size;

        FileInfo(String path, long size) {
            this.path = path;
            this.size = size;
        }

        @Override
        public String toString() {
            return path + " | " + readableFileSize(size);
        }
    }

    // 可读文件大小
    private static String readableFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    // 扫描目录
    private static void scanFolder(File folder, long minSize, List<FileInfo> results) {
        if (folder == null || !folder.exists() || !folder.isDirectory()) return;

        File[] files = folder.listFiles();
        if (files == null) return;

        for (File file : files) {
            try {
                if (file.isFile()) {
                    if (file.length() >= minSize) { // 判断大文件
                        results.add(new FileInfo(file.getAbsolutePath(), file.length()));
                    }
                } else if (file.isDirectory()) {
                    scanFolder(file, minSize, results); // 递归扫描
                }
            } catch (Exception e) {
                // 忽略无法访问的文件夹/文件
            }
        }
    }

    public static void main(String[] args) {
        // 扫描 C 盘，最小文件大小设置为 100MB
        long minSize = 100L * 1024 * 1024;
        List<FileInfo> largeFiles = new ArrayList<>();

        File root = new File("C:\\");
        System.out.println("开始扫描 C 盘大文件...");
        scanFolder(root, minSize, largeFiles);

        System.out.println("扫描完成，共找到 " + largeFiles.size() + " 个大文件：");
        for (FileInfo info : largeFiles) {
            System.out.println(info);
        }
    }
}
